﻿using Autofac.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Threading.Tasks;
using VOL.Core.Controllers.Basic;
using VOL.Core.Filters;
using VOL.Core.ObjectActionValidator;
using VOL.Core.Services;
using VOL.Entity.DomainModels;
using VOL.System.IRepositories;
using VOL.System.IServices;

using VOL.Core.Enums;
using VOL.Core.Utilities;
using Org.BouncyCastle.Crypto.IO;
using VOL.WebApi.Controllers.WorkOrder;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using VOL.Core.Configuration;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.CacheManager;
using VOL.System.Services;
using VOL.Entity.VM;
using Microsoft.Extensions.Configuration;
using NPOI.HSSF.UserModel;
using AutoMapper;
using EasyNetQ.Internals;
using Newtonsoft.Json.Linq;
using S7.Net;
using VOL.WebApi.Extensions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Tea;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using NPOI.HSSF.Record;
using VOL.Core.BaseInterface;
using System.Net.Mail;
using Org.BouncyCastle.Crypto.Engines;
using System.Data.Common;
using System.Diagnostics;
using SysIO = System.IO;


using System.Diagnostics;
using TDengine.Driver;
using TDengine.Driver.Client;
using Confluent.Kafka;
using FluentFTP.Helpers;
using System.Numerics;
using Newtonsoft.Json;
using System.IO;
using RFID.UHFReader;
using Org.BouncyCastle.Utilities.Net;
using RFIDlib;
using System.Threading;

namespace VOL.WebApi.Controllers
{
  
    /// <summary>
    /// 邮件发送，短信发送，日志记录
    /// </summary>
    public partial class A_UpperComputerController :
    //ApiBaseController<Iupper_work_orderService>
    ApiBaseController<ISys_UserService>
    {
        #region 排产检查
        /// <summary>
        /// 工单检查
        /// </summary>
        /// <param name="OrderPlanCheck"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPlanCheck")]
        public async Task<IActionResult> OrderPlanCheck([FromBody] PLAN_WORK_ORDER equ_TASKVM)
        {
            var rs = await userService.OrderPlanCheck(equ_TASKVM);
            return Json(rs);
        }
        #endregion
        #region 工单检查
        /// <summary>
        /// 工单检查
        /// </summary>
        /// <param name="OrderCheck"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderCheck")]
        public async Task<IActionResult> OrderCheck([FromBody] PLAN_WORK_ORDER equ_TASKVM)
        {
            var rs = await userService.OrderCheck(equ_TASKVM);
            return Json(rs);
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("Flow"), HttpPost]
        [ActionPermission(ActionPermissionOptions.Update)]
        public async Task<object> Flow([FromBody] PROC_PROCESS taskOptions)
        {
              return await userService.Flow(taskOptions);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("ReadRFIDTest")]
        public async Task<IActionResult> ReadRFIDTest(string coderfid)
        {
            WebResponseContent rs1 = new WebResponseContent();
            R2KReader objreader = new R2KReader();
            RfidMessage rfidMessage = new RfidMessage();
            string Port= "502"; 
            string IpAddress = "192.168.1.160";
            try
            {

                string data = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";
                string hexString = Convert.ToString(Convert.ToInt32( coderfid), 16);
                // 因为最后一个部分后面没有空格，所以最后一个元素会被截断。我们可以手动添加
                // 分割字符串

                string outStr = string.Empty;
                string outStrLast = string.Empty;
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
              //  rfidMessage.button_accessExec_Click(objreader, "A1 29 34 00");
                
                //string ReaderModelText = objreader.ProductModel_str;//显示产品型号
                //string ReaderSNText = objreader.ProductSN_str;      //显示产品序列号
                //string ReaderFirmwareText = objreader.FirmwareVersion_str;//显示固件版本

                rfidMessage.ReadRFID(objreader, out outStr, "EPC区");
                rfidMessage.button_Disconnect_TCP_Click(objreader);
                data = outStr;
                string[] parts = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 使用空格分割并移除空项
                string originalString = string.Join(" ", parts); // 重新组合成一个字符串
                string replacement = hexString.PadLeft(8, '0').ToUpper(); ; // 替换的字符串

                string str= FormatHexString(replacement);

                int startIndex = 11; // 起始索引（注意：基于0开始）
                int length = 11; // 需要替换的长度

                // 删除原有的部分并插入新的字符串
                string newString = originalString.Remove(startIndex, length+1);

               // string newString1 = "EA AB 34 00 00 00 00 7E 00 00 00 7E 00 00 00 01";// newString.Insert(startIndex, replacement);
               string newString1 = newString.Insert(startIndex, " "+str+"");


                //写入标签内存


                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
                 rfidMessage.button_accessExec_Click(objreader, newString1);

                rfidMessage.button_Disconnect_TCP_Click(objreader);

                //读取标签内存
                rfidMessage.button_Connect_TCP_Click(objreader, Port.ToString(), IpAddress);
          

                rfidMessage.ReadRFID(objreader, out outStrLast, "EPC区");


                rfidMessage.button_Disconnect_TCP_Click(objreader);

                if(outStrLast== newString1)
                {
                    rs1.Status = true;
                    rs1.Message = "写入成功";
                    rs1.Data = outStrLast;
                  
                }
                else
                {
                    rs1.Status = false;
                    rs1.Message = "写入失败";
                    rs1.Data = outStrLast;
        
                }
            
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                  rfidMessage.button_Disconnect_TCP_Click(objreader);
            }

            return Json(rs1);
        }
        /// <summary>
        /// 将连续十六进制字符串转换为带空格的格式
        /// </summary>
        /// <param name="input">连续无分隔的十六进制字符串 (如"0000007E")</param>
        /// <returns>空格分隔的格式 (如"00 00 00 7E")</returns>
        public static string FormatHexString(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
                throw new ArgumentException("输入不能为空或空白");

            if (input.Length % 2 != 0)
                throw new ArgumentException("输入长度必须为偶数");

            // 按每2字符分割并转换为大写
            return string.Join(" ",
                Enumerable.Range(0, input.Length / 2)
                          .Select(i => input
                              .Substring(i * 2, 2)
                              .ToUpperInvariant()));
        }
        static byte[] HexStringToByteArray(string hex)
        {
            if (hex.Length % 2 != 0)
                throw new ArgumentException(String.Format("The binary key cannot have an odd number of digits: {0}", hex));

            byte[] arr = new byte[hex.Length >> 1];

            for (int i = 0; i < hex.Length >> 1; ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i * 2]) << 4) + GetHexVal(hex[i * 2 + 1]));
            }

            return arr;
        }

        static int GetHexVal(char hex)
        {
            int val = hex;
            // For uppercase A-F letters:
            return val - (val < 58 ? 48 : 55);
            // For lowercase a-f letters:
            // return val - (val < 58 ? 48 : 87);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        [HttpPost, Route("ReadSizeTxt")]
        public async Task<IActionResult> ReadSizeTxt([FromBody] PLAN_WORK_ORDER equ_TASKVM)
        {
            WebResponseContent rs1 = new WebResponseContent();

            try
            {

                string filePath = @"C:\FTP_Remote_Path\O0201.CNC"; // 指定文件路径
                                                                   //  int lineCount = File.ReadAllLines(filePath).Length; // 使用ReadAllLines方法并获取长度
                if (!SysIO.File.Exists(filePath))
                {
                    Console.WriteLine("错误：文件不存在！");
                  
                }
                // 检查目录下所有txt文件的大小
                foreach (var file in Directory.GetFiles(@"C:\FTP_Remote_Path\", "*.CNC"))
                {
                    // 处理每个文件
                    SysIO.FileInfo fileInfo = new SysIO.FileInfo(file);

                    // 验证文件扩展名（可选）
                    if (SysIO.Path.GetExtension(file).ToUpper() != ".CNC")
                    {
                        Console.WriteLine("警告：文件不是TXT格式！");
                    }

                    // 获取文件大小并转换单位
                    string formattedSize = FormatFileSize(fileInfo.Length);
                }

                
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }

            return Json(rs1);
        }
        static string FormatFileSize(long bytes)
        {
            string[] units = { "B", "KB", "MB", "GB", "TB" };
            int unitIndex = 0;
            double size = bytes;

            while (size >= 1024 && unitIndex < units.Length - 1)
            {
                size /= 1024;
                unitIndex++;
            }

            return $"{size:0.##} {units[unitIndex]}";
        }
        /// <summary>
        /// txt文件读取
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>

        [HttpPost, Route("ReadTxt")]
        public async Task<IActionResult> ReadTxt([FromBody] PLAN_WORK_ORDER equ_TASKVM)
        {
            WebResponseContent rs1= new WebResponseContent();

            try
            {
      
                string filePath = @"C:\FTP_Remote_Path\O0201.CNC"; // 指定文件路径
              //  int lineCount = File.ReadAllLines(filePath).Length; // 使用ReadAllLines方法并获取长度
                using (SysIO.StreamReader reader = new SysIO.StreamReader(filePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }

            return Json(rs1);
        }
        /// <summary>
        /// txt文件写入
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("WriteTxt")]
        public async Task<IActionResult> WriteTxt()
        {
            WebResponseContent rs1 = new WebResponseContent();

            try
            {

                string filePath = @"C:\FTP_Remote_Path\O1000.CNC"; // 指定文件路径
                //  int lineCount = File.ReadAllLines(filePath).Length; // 使用ReadAllLines方法并获取长度
           //     tring filePath = @"C:\path\to\your\file.txt"; // 指定文件路径
                string content = "Hello, World!"; // 要写入的内容

                using (SysIO.StreamWriter writer = new SysIO.StreamWriter(filePath))
                {
                    writer.WriteLine(content); // 写入内容并换行
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }

            return Json(rs1);
        }


    }


    public class RfidMessage
    {

        private List<byte> _executeDataList = new List<byte>();
        IConfiguration _configuration;

        private ReadMode_enum ReaderMode;

        private static RfidMessage _instance;
        private static readonly object locker = new object();

        public RfidMessage()
        {

        }
        //初始化内容显示
        private void InitInfoDisp()
        {
            //   ReadTag_GetReadMode();//获取读写器工作模式
            //ReaderModelText.Text = objreader.ProductModel_str;//显示产品型号
            //ReaderSNText.Text = objreader.ProductSN_str;      //显示产品序列号
            //ReaderFirmwareText.Text = objreader.FirmwareVersion_str;//显示固件版本
            // ProductModelLimit();//根据读写器型号，屏蔽相应型号没有的功能      
        }
        //获取读卡模式
        private bool ReadTag_GetReadMode(R2KReader objreader)
        {
            Status_enum retval;
            UInt16 WordMode = 0;
            retval = objreader.GetLogisticsWorkMode(ref WordMode);
            if (retval != Status_enum.SUCCESS)
            {
                //   SetStatus("获取工作模式参数失败", Color.Red);
                return false;
            }

            if (WordMode == 2)
            {
                ReaderMode = ReadMode_enum.AUTOREAD_LOGISTICS;
            }
            else if (WordMode == 1)
            {
                ReaderMode = ReadMode_enum.AUTOREAD_LINEBODY;
            }
            else
            {
                ReaderMode = ReadMode_enum.AT_MODE;
            }

            if (ReaderMode == ReadMode_enum.AUTOREAD_LOGISTICS)
            {
                //   label_ReadMode.Text = "自动-物流";
                //   label_ReadMode.ForeColor = Color.OrangeRed;
            }
            else if (ReaderMode == ReadMode_enum.AUTOREAD_LINEBODY)
            {
                //   label_ReadMode.Text = "自动-线体";
                //   label_ReadMode.ForeColor = Color.Black;
                UInt16 ReadTime = 0;
                retval = objreader.GetReadSingleTime(ref ReadTime);
                if (retval != Status_enum.SUCCESS)
                {
                    //    SetStatus("获取工作模式参数失败", Color.Red);
                    return false;
                }
                //  ReadSingleTime = ReadTime;
            }
            else
            {
                //   label_ReadMode.Text = "应答模式";
                //    label_ReadMode.ForeColor = Color.Black;
                UInt16 ReadTime = 0;
                retval = objreader.GetReadSingleTime(ref ReadTime);
                if (retval != Status_enum.SUCCESS)
                {
                    //    SetStatus("获取工作模式参数失败", Color.Red);
                    return false;
                }
                //     ReadSingleTime = ReadTime;

            }
            return true;
        }
        public void button_Connect_TCP_Click(R2KReader objreader, string TcpPort, string tB_ip)
        {
            try
            {

                string portOrbaud = TcpPort;
                if (!objreader.Connect(tB_ip, int.Parse(portOrbaud)))
                {
                  //  MessageBox.Show("连接失败!");
                    return;
                }
                ReadTag_GetReadMode(objreader);//获取读写器工作模式
                string ReaderModelText = objreader.ProductModel_str;//显示产品型号
                string ReaderSNText = objreader.ProductSN_str;      //显示产品序列号
                string ReaderFirmwareText = objreader.FirmwareVersion_str;//显示固件版本
                //InitInfoDisp();

                //  SetStatus("已建立连接...", Color.Green);
                //  tsmi_search.Enabled = false;//建立TCP连接后，关闭UDP搜索读写器功能
                //   toolStripMenuItem_AccessTest.Enabled = true;
                //  tB_ip.Enabled = false;
                //   button_Connect_TCP.Enabled = false;
                //    TcpPort.Enabled = false;
            }
            catch
            {
                //   tsmi_search.Enabled = true;
                //  SetStatus("连接失败...", Color.Red);
            }
        }

        public void button_Disconnect_TCP_Click(R2KReader objreader)
        {
            //   tsmi_search.Enabled = true;//恢复UDP搜索读写器功能
            //  toolStripMenuItem_AccessTest.Enabled = false;
            //  SerialMask(false);         //恢复串口连接功能
            objreader.DisConnect();    //释放已连接的资源 
                                       //   SetStatus("已断开连接...", Color.Black);
                                    //   tB_ip.Enabled = true;
                                       //   button_Connect_TCP.Enabled = true;
        }
        /// <summary>
        /// 写入标签内存
        /// </summary>
        /// <param name="objreader"></param>
        /// <param name="datastr"></param>
        public void button_accessExec_Click(R2KReader objreader, string datastr)
        {
            AccessWriteEPC(objreader, datastr);
            //if (comboBox_accessType.Text == "读")
            //{
            //    AccessRead();
            //}
            //else if (comboBox_accessType.Text == "写")
            //{
            //    AccessWrite();
            //}
            //else if (comboBox_accessType.Text == "写EPC号")
            //{
            //    AccessWriteEPC();
            //}
            //else
            //{
            //    SetStatus("操作选项错误！", Color.Red);
            //}
        }
        /// <summary>
        /// 读RFID
        /// </summary>
        /// <param name="objreader"></param>
        /// <param name="outStr"></param>
        /// <param name="comboBox_accessType"></param>
        public void ReadRFID(R2KReader objreader, out string outStr, string comboBox_accessType = "USER区")
        {
            outStr = string.Empty;
            AccessRead(objreader, comboBox_accessType, out outStr);



            //else
            //{
            //    SetStatus("操作选项错误！", Color.Red);
            //}
        }
        //读标签内存
        private void ReadTagMemory(R2KReader objreader, Gen2.Bank bank, string textBox_AccessOffset, string textBox_AccessLen, bool radioButton_FirstResponse, out string outStr)
        {
            outStr = string.Empty;
            Status_enum retval;
            byte[] data = new byte[256];
            AccessTagMask TagMask = new AccessTagMask();
            try
            {
                //if (textBox_AccessOffset.Text.Equals("") || textBox_AccessLen.Text.Equals(""))
                //{
                //    SetStatus("偏移字地址或者读取字长度不能为空！", Color.Red);
                //    return;
                //}
                int ReadWordlen = int.Parse(textBox_AccessLen);
                int ReadOffset = int.Parse(textBox_AccessOffset);
                int ant = GetAccessAnt();
                AccessMask_enum TagListIndex;

                if (radioButton_FirstResponse == true)
                {
                    //采用第一张响应的标签
                    TagListIndex = AccessMask_enum.NO_MASK;
                }
                else
                {
                    ////使用标签筛选
                    //if (TagAccessListSelection.Text == "选择标签")
                    //{
                    //    SetStatus("请选择需要筛选的标签！", Color.Red);
                    //    return;
                    //}

                    TagListIndex = AccessMask_enum.ENABLE_MASK;
                    //TagMask.Mask_Bank = Gen2.Bank.EPC;
                    //TagMask.Mask_WordPtr = 2;//EPC区的前4个字节是CRC和PC码，后面才是EPC码本体
                    //TagMask.Mask_WordLen = (UInt16)(TagAccessListSelection.Text.Length / 4);//字单位
                    //TagMask.Mask_Data = Tools.HexStringToByte(TagAccessListSelection.Text, 0, TagAccessListSelection.Text.Length / 2);//字节单位



                }


                if (ReadWordlen == 0)
                {
                    //SetStatus("读取字长度不能为0！", Color.Red);
                    return;
                }
                if (ReadWordlen > 32)
                {
                    ReadWordlen = 32;
                    //textBox_AccessLen.Text = "32";//最多一次读取32个字
                }

                if (TagListIndex == AccessMask_enum.ENABLE_MASK)
                {
                    retval = objreader.SetAccessMask(TagMask);
                    if (retval != Status_enum.SUCCESS)
                    {
                        //textBoxDatas_access.Text = "掩码条件发送失败!";
                        //SetStatus("掩码条件发送失败!", Color.Red);
                    }
                }

                retval = objreader.SetReBootAutoReadMulAnt((UInt16)ant, Save_enum.No_Save);
                if (retval != Status_enum.SUCCESS)
                {
                    //SetStatus("天数设置失败!", Color.Red);
                    return;
                }
                Thread.Sleep(50);
                retval = objreader.AccessReadTagMemory(TagListIndex, ant, bank, ReadOffset, ReadWordlen, ref data);
                if (retval != Status_enum.SUCCESS)
                {
                    //textBoxDatas_access.Text = "读取失败！";
                    //SetStatus("标签内存读取失败!", Color.Red);
                }
                else
                {
                    outStr = Tools.ByteToHexString(data, 0, ReadWordlen * 2, " ");
                    //SetStatus("标签内存读取成功！", Color.Green);
                }
            }
            catch (Exception e)
            {
                //SetStatus("读取失败,输入的数据格式不正确!", Color.Red);
              //  MessageBox.Show(e.Message);
            }
        }
        void AccessRead(R2KReader objreader, string comboBox_MemoryArea, out string outStr)
        {
            outStr = string.Empty;
            switch (comboBox_MemoryArea)
            {
                case "EPC区":
                    ReadTagMemory(objreader, Gen2.Bank.EPC, "2", "8", true, out outStr);
                    break;
                case "TID区":
                    ReadTagMemory(objreader, Gen2.Bank.TID, "0", "4", true, out outStr);
                    break;
                case "USER区":
                    ReadTagMemory(objreader, Gen2.Bank.USER, "0", "2", true, out outStr);
                    break;
                default:
                    break;
            }
        }
        //获取有效的访问天线
        public int GetAccessAnt()
        {

            //if (AccessAnt4.Checked == true)
            //{
            //    return (0x01 << 3);
            //}
            //else if (AccessAnt3.Checked == true)
            //{
            //    return (0x01 << 2);
            //}
            //else if (AccessAnt2.Checked == true)
            //{
            //    return (0x01 << 1);
            //}
            //else
            //{
            //    return 0x01;
            //}
            return 0x01;
        }
        private void WriteTagMemory(Gen2.Bank bank, R2KReader objreader, string textBox_AccessLen, string textBox_AccessOffset, string textBoxDatas_access)
        {
            Status_enum retval;
            byte[] datas = new byte[256];
            AccessTagMask TagMask = new AccessTagMask();
            try
            {
                int ReadWordlen = int.Parse(textBox_AccessLen);
                int ReadOffset = int.Parse(textBox_AccessOffset);
                AccessMask_enum TagListIndex;


                //if (radioButton_FirstResponse.Checked == true)
                //{
                //第一张响应的标签
                TagListIndex = AccessMask_enum.NO_MASK;
                //}
                //else
                //{
                //    //筛选方式
                //    if (TagAccessListSelection.Text == "选择标签")
                //    {
                //        SetStatus("请选择需要筛选的标签！", Color.Red);
                //        return;
                //    }
                //    TagListIndex = AccessMask_enum.ENABLE_MASK;
                //    TagListIndex = AccessMask_enum.ENABLE_MASK;
                //    TagMask.Mask_Bank = Gen2.Bank.EPC;
                //    TagMask.Mask_WordPtr = 2;//EPC区的前4个字节是CRC和PC码，后面才是EPC码本体
                //    TagMask.Mask_WordLen = (UInt16)(TagAccessListSelection.Text.Length / 4);//2个字符为一个字节
                //    TagMask.Mask_Data = Tools.HexStringToByte(TagAccessListSelection.Text, 0, TagAccessListSelection.Text.Length / 2);

                //}


                int ant = GetAccessAnt();
                if (ReadWordlen == 0)
                {
                    //   SetStatus("写入字长度不能为0！", Color.Red);
                    return;
                }
                if (ReadWordlen > 32)
                {
                    ReadWordlen = 32;
                    textBox_AccessLen = "32";//最多一次读取32个字
                }



                string tmp = textBoxDatas_access;
                if (tmp.Replace(" ", "").Length == 0)
                {
                 //   MessageBox.Show("写入内容不能为空");
                    return;
                }
                byte[] writedata = Tools.HexStringToByte(textBoxDatas_access, 0, ReadWordlen * 2);
                if (writedata.Length < ReadWordlen * 2)
                {
                 //   MessageBox.Show("数据不足!");
                    return;
                }

                retval = objreader.SetReBootAutoReadMulAnt((UInt16)ant, Save_enum.No_Save);
                if (retval != Status_enum.SUCCESS)
                {
                    //SetStatus("天数设置失败!", Color.Red);
                    return;
                }
                Thread.Sleep(50);
                retval = objreader.AccessWriteTagMemory(TagListIndex, ant, bank, ReadOffset, ReadWordlen, writedata);
                if (retval == Status_enum.SUCCESS)
                {
                    //访问请求执行完毕   
                    //SetStatus("标签内存写入成功！", Color.Green);
                }
                else
                {
                    //SetStatus("标签内存写入失败！", Color.Red);
                }
            }
            catch (Exception e)
            {
                //SetStatus("写入失败,输入的数据格式不正确!", Color.Red);
            //    MessageBox.Show(e.Message);
            }
        }
        /// <summary>
        /// 写RFID
        /// </summary>
        /// <param name="objreader"></param>
        /// <param name="writeStr"></param>
        /// <param name="comboBox_MemoryArea"></param>
        public void AccessWrite(R2KReader objreader, string writeStr, string comboBox_MemoryArea = "USER区")
        {
            switch (comboBox_MemoryArea)
            {
                //case "EPC区":

                //    WriteTagMemory(Gen2.Bank.EPC, objreader,"2","0",writeStr);
                //    break;
                case "USER区":
                    WriteTagMemory(Gen2.Bank.USER, objreader, "2", "0", writeStr);
                    break;
                default:
                    break;
            }
        }
        #region 写EPC号

        private void AccessWriteEPC(R2KReader objreader, string datastr)
        {
            Status_enum retval;
            byte[] datas = new byte[256];
            try
            {
                //string datastr = string.Empty;// textBoxDatas_access.Text.ToString();

                //datastr.Replace(" ", "");
                if ((datastr.Length == 0) || (datastr == null))
                {
                    // MessageBox.Show("写入内容不能为空");
                    return;
                }
                datastr = datastr.Replace(" ", "");
                if (datastr.Length % 4 != 0)
                {
                 //   MessageBox.Show("写入内容的字节长度必须为偶数！");
                    // SetStatus("数据长度不符合规则!", Color.Red);
                    return;
                }
                byte[] writedata = Tools.HexStringToByte(datastr, 0, datastr.Length / 2);//datastr为字符串，两个字符表示一个字节

                int ant = GetAccessAnt();
                retval = objreader.SetReBootAutoReadMulAnt((UInt16)ant, Save_enum.No_Save);
                if (retval != Status_enum.SUCCESS)
                {
                    //  SetStatus("天数设置失败!", Color.Red);
                    return;
                }
                Thread.Sleep(50);

                retval = objreader.WriteTagEPC(ant, writedata, writedata.Length / 2);
                if (retval == Status_enum.SUCCESS)
                {
                    //访问请求执行完毕   
                    //   SetStatus("EPC号写入成功！", Color.Green);
                }
                else
                {
                    //   SetStatus("EPC号写入失败！", Color.Red);
                }
            }
            catch
            {
                //   SetStatus("格式错误，写EPC号失败！", Color.Red);
            }
            


        }
        #endregion


    }




}
